# -*- coding:utf-8 -*-
import logging
import os
import yaml
import base64
import requests


def _read_config():
    confDirPath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "conf")
    confDir, _, confFileList = list(os.walk(confDirPath))[0]
    confDict = {}
    for confFile in confFileList:
        r = load_yml(ymlFilePath=os.path.join(confDir, confFile))
        confDict.update(r)
    return confDict


def load_yml(ymlFilePath):
    with open(os.path.join(ymlFilePath), "r", encoding="utf-8") as f:
        return yaml.full_load(f)


def decryption_conf(conf):
    confDict = conf
    port = f":{str(confDict.get('serverPort'))}" if confDict.get("serverPort") else ""
    url = "http://" + confDict.get("serverHost") + port + confDict.get("apiUrl")
    params = {
        "host": confDict.get("host"),
        "userName": confDict.get("userName"),
        "password": confDict.get("password"),
        "user": confDict.get("user")
    }
    exec('resp = requests.request(' + f'"{confDict.get("method")}","{url}", params={params})')
    dbConf = eval("resp").json()
    return dbConf.get("data")


conf = _read_config()
dbConf = decryption_conf(conf)


class Config(object):

    """项目配置"""
    DEBUG = True

    SECRET_KEY = os.urandom(24)
    JSON_AS_ASCII = False

    """数据库配置"""
    SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{dbConf.get('userName')}:{dbConf.get('password')}@" \
                              f"{dbConf.get('host')}" \
                              f":{conf.get('port')}" \
                              f"/{conf.get('dbName')}"
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True

    """日志配置"""
    LOG_LEVEL = logging.DEBUG
    LOG_PATH = "logs/zfs-data-server.out"
    LOG_FILE_SIZE = 1024 * 1024 * 100
    LOG_FILE_MAX_COUNT = 5
    LOG_ENCODING = "utf-8"


class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True


class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False
    LOG_LEVEL = logging.INFO


class TestingConfig(Config):
    """单元测试环境配置"""
    DEBUG = True
    TESTING = True


config = {
    "development": DevelopmentConfig,
    "production": ProductionConfig,
    "testing": TestingConfig
}
